package com.example.home_stretch;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;

import org.litepal.LitePal;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;

public class Account_management extends AppCompatActivity {
    private String yy,s1,s2,s3;
    @BindView(R.id.plcz)
    TextView plcz;
    @BindView(R.id.tv_czjl)
    TextView tvCzjl;
    @BindView(R.id.lv_zhye)
    ListView lvZhye;
    private List<Account_management_list> account_list = new ArrayList<>();
    private List<Integer> checkboxID = new ArrayList<>();//储存checkbox的值

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.account_management);
        ButterKnife.bind(this);
        initview();
        initsqp1();
    }
    //查询数据库
    private void initsqp1(){
        List<Book> all = LitePal.findAll(Book.class);
        Log.i("TAG", "initsqp1123"+all.size());

    }
    //把数据都储存在数据库里
    private void initsql(){
        LitePal.getDatabase();
        Book book=new Book();
        //存入实时时间
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy.MM.dd HH.mm");
        Date data=new Date(System.currentTimeMillis());
        book.setClbh(Integer.parseInt(s1));
        book.setCzje(Integer.parseInt(yy));
        book.setCzye(Integer.parseInt(s3));
        book.setName(s2);
        book.setTime(simpleDateFormat.format(data));
        //查询数据库
        List<Book> all = LitePal.findAll(Book.class);
        for (Book book1:all){
            Log.i("TAG", "initsql1丨"+book1.getName());
        }
    }
    //设置输入框第一个数字不能为0
    private TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            String text = s.toString();
            if (s.toString().length() == 1 && text.equals("0")) {
                s.clear();
                Toast.makeText(Account_management.this, "金额不能以0开头，请重新输入", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @OnClick(R.id.tv_czjl)
    public void onViewClicked1() {
        startActivity(new Intent(Account_management.this, Czjl.class));
    }
    //post请求
    private interface BlogServicea {
        @POST("charge")
        Call<ResponseBody> getBloga(@Body RequestBody user);
    }

    private void initData(final String yy, int i) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .build();
        Map<String, String> map = new HashMap<>();
        if (i == -1) {
            //拼接字符串
            StringBuffer car = new StringBuffer();
            for (int u = 0; u < checkboxID.size(); u++) {
                //拼接，只是增加而不是替换append
                car.append("&" + account_list.get(0).getData().get(checkboxID.get(u)).getCarno());
            }
            s1 = String.valueOf(car);
            s2 = account_list.get(0).getData().get(checkboxID.get(0)).getWho();
            map.put("who",s2 );
            //第一个&替换成""
            map.put("carno", s1.replaceFirst("&", ""));
        } else {
            s2=account_list.get(0).getData().get(i).getWho();
            s1=account_list.get(0).getData().get(i).getCarno();
            map.put("who", s2);
            map.put("carno", s1);
        }
        map.put("amount", yy);
        Gson gson = new Gson();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), gson.toJson(map));
        BlogServicea service = retrofit.create(BlogServicea.class);
        Call<ResponseBody> call = service.getBloga(requestBody);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                checkboxID = new ArrayList<>();
                initview();
//                try {
//                    account_list = new ArrayList<>();
//                    String string = response.body().string();
//                    Account_management_list account_management_list = new Gson().fromJson(string, Account_management_list.class);
//                    account_list.add(account_management_list);
//                    for (int f=0;f<account_list.get(0).getData().size();f++){
//                    s3=account_list.get(0).getData().get(f).getAmount()+"";
//                    initsql();
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
        }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Toast.makeText(Account_management.this, "充值失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    class ViewHolder1 {
        @BindView(R.id.tv_clbh)
        TextView tvClbh;
        @BindView(R.id.ed_czk)
        EditText edCzk;
        @BindView(R.id.bu_recharge)
        Button buRecharge;
        @BindView(R.id.bu_cancel)
        Button buCancel;
        ViewHolder1(View view) {
            ButterKnife.bind(this, view);
        }
    }

    //设置弹窗
    private void initdata(final int i) {
        if (checkboxID.size() == 0) {
            Toast.makeText(this, "请选择车辆进行充值", Toast.LENGTH_SHORT).show();
        } else {
            AlertDialog.Builder setDeBugDialog = new AlertDialog.Builder(this);
            final View dialogView = LayoutInflater.from(this).inflate(R.layout.recharge_page, null);
            ViewHolder1 viewHolder1 = new ViewHolder1(dialogView);
            setDeBugDialog.setView(dialogView);
            setDeBugDialog.setCancelable(false);
            final AlertDialog customAlert = setDeBugDialog.show();
            dialogView.findViewById(R.id.bu_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //取消的方法
                    customAlert.dismiss();
                }
            });
            viewHolder1.edCzk.addTextChangedListener(mTextWatcher);
            if (i == -1) {
                for (int u = 0; u < checkboxID.size(); u++) {
                    //拼接车牌号，只是增加而不是替换append
                    viewHolder1.tvClbh.append(account_list.get(0).getData().get(checkboxID.get(u)).getCarno() + "|");
                }
            } else {
                viewHolder1.tvClbh.setText(account_list.get(0).getData().get(i).getCarno() + "");
            }
            viewHolder1.buRecharge.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                     yy = viewHolder1.edCzk.getText().toString().trim();
                    initData(yy, i);
                    if (viewHolder1.edCzk.length() == 0) {
                        Toast.makeText(Account_management.this, "充值金额不能为空", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(Account_management.this, "充值成功", Toast.LENGTH_SHORT).show();
                    }
                    viewHolder1.edCzk.setText("");
                    account_list = new ArrayList<>();
                }
            });
        }
    }
    //批量充值的点击按钮，-1为标记，因为initdatA(final int i)是一个整数
    @OnClick(R.id.plcz)
    public void onViewClicked() {
        initdata(-1);
    }
    public interface BlogService {
        @GET("carlist")
        Call<ResponseBody> getBlog();
    }
    private void initview() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .build();
        BlogService service = retrofit.create(BlogService.class);
        Call<ResponseBody> call = service.getBlog();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Gson gson = new Gson();
                Account_management_list carlist = null;
                try {
                    carlist = gson.fromJson(response.body().string(), Account_management_list.class);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                account_list.add(carlist);
                lvZhye.setAdapter(new MeAdapter());
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }
    class MeAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return account_list.get(0).getData().size();
        }
        @Override
        public Object getItem(int position) {
            return null;
        }
        @Override
        public long getItemId(int position) {
            return 0;
        }
        class ViewHolder {
            @BindView(R.id.tv_id)
            TextView tvId;
            @BindView(R.id.tv_ye)
            TextView tvYe;
            @BindView(R.id.tv_xx)
            CheckBox tvXx;
            @BindView(R.id.tv_cz)
            Button tvCz;
            ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view1 = View.inflate(Account_management.this, R.layout.account_management_one, null);
            ViewHolder viewHolder = new ViewHolder(view1);
            viewHolder.tvCz.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    initdata(position);
                }
            });
            viewHolder.tvId.setText(position + 1 + "");
            viewHolder.tvYe.setText(account_list.get(0).getData().get(position).getAmount() + "");
            //复选框的点击事件，点击第一回添加到集合里面，第二回移除
            viewHolder.tvXx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean b) {
                    if (b) {
                        checkboxID.add(position);
                    } else {
                        //移除
                        checkboxID.remove(new Integer(position));
                    }
                }
            });
            return view1;
        }
    }

}
